HJS

use API (React 19)

React 19에서 새롭게 도입된 use API는 비동기 데이터를 더 쉽게 다룰 수 있도록 도와주는 훅입니다. 기존에는 useEffect + useState를 조합해야 했지만, use를 사용하면 더 간결한 코드로 데이터를 가져올 수 있고, Suspense와 자연스럽게 결합됩니다.

💡 주요 특징

1️⃣ 기본 사용법

🔹 기본적인 use API 사용법

import { use, Suspsense } from "react";

function Comments({ commentsPromise }) {
  const comments = use(commentsPromise);
  reuturn comments.map((comment) => <p key={commnent.id}>{comment}</p>)
}
function Page({ commentsPromise }) {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Comments commentsPromise={commentsPromise}> />
    </Suspense>
  )
}

✔️ use를 사용하면 useEffect 없이도 데이터를 직접 가져올 수 있습니다.
✔️ Suspsen와 함께 사용하면 로딩 상태를 자동으로 관리할 수 있습니다.




2️⃣ 기존 방식과의 차이점

🔹 기존 방식 (useEffect + useState 사용)

import { useState, useEffect } from "react";

function Comments({ commentsPromise }) {
  const [comments, setComments] = useState(null);

  useEffect(() => {
    commentsPromise.then(setComments);
  }, [commentsPromise]);

  if (!comments) {
    return <div>Loading...</div>;
  }

  return comments.map((comment) => <p key={comment.id}>{comment}</p>);
}

✔️ useEffectuseState를 사용해야 하고, 로딩 상태를 따로 관리해야 합니다.

🔹 use API를 사용한 방식

import { use, Suspense } from "react";

function Comments({ commentsPromise }) {
  const comments = use(commentsPromise);
  return comments.map((comment) => <p key={comment.id}>{comment}</p>);
}

✔️ use를 사용하면 비동기 데이터가 자동으로 처리됩니다.
✔️ useStateuseEffect 없이도 데이터를 가져올 수 있습니다.




3️⃣ 컨텍스트(Context)에서 use 활용

use컨텍스트 값을 조건부로 읽을 수 있도록 도와줍니다.
기존 useContext는 항상 실행되지만, use를 사용하면 특정 조건에서만 컨텍스트르 가져올 수 있습니다.

🔹 기존 useContext 사용 방식

import { useContext } from "react";
import ThemeContext from "./ThemeContext";

function Haeding({ children }) {
  const theme = useContext(ThemeContext);
  return <h1 style={{ color: theme.color }}>{children}</h1>;
}

✔️ 항상 컨텍스트 값을 가져오기 때문에, 조건부 렌더링이 어려움

🔹 use API를 사용한 방식

import { use } from "react";
import ThemeContext from "./ThemeContext";

function Heading({ children }) {
  if (!children) return null;
  const theme = use(ThemeContext);
  return <h1 style={{ color: theme.color }}>{children}</h1>;
}

✔️ 특정 조건(if (!children) return null;)에서만 컨텍스트를 가져올 수 있어 더 유연함




4️⃣ use API 사용 시 주의할 점

❌ 렌더링 중 새로운 프로미스를 만들면 안 됨

function Comments() {
  const comments = use(fetchComments()); // ❌ 이렇게 하면 안 됨
  return comments.map((comment) => <p key={comment.id}>{comment}</p>);
}

✔️ use이미 생성된 프로미스만 사용 가능합니다.
✔️ 해결 방법: 프로미스를 미리 생성한 후 전달해야 합니다.

const commentsPromise = fetchComments();

function Comments() {
  const comments = use(commentsPromise); // ✅ 미리 생성된 프로미스를 사용
  return comments.map((comment) => <p key={comment.id}>{comment}</p>);
}

❌ Suspense 없이 사용할 수 없음

✔️ useSuspense와 함께 사용해야 정상 동작합니다.

✅ React Server Components에서 활용 가능

✔️ 서버 사이드 렌더링(SSR) 환경에서도 유용하게 활용 가능